package com.sskj.ws.listener;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.sskj.common.constant.RabbitMQConstant;
import com.sskj.common.dto.DeviceShadow;
import com.sskj.common.util.StrUtil;
import com.sskj.ws.factory.DeviceSubscriptionFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

// 设备监听
@Slf4j
@Component
public class DeviceListener {

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private DeviceSubscriptionFactory deviceSubscriptionFactory;

    @RabbitListener(queues = RabbitMQConstant.IOT_QUEUE)
    public void propMessage(String message) {
        if (StrUtil.isBlank(message)) {
            try {
                DeviceShadow deviceShadow = objectMapper.readValue(message, DeviceShadow.class);

                if (StrUtil.isNotBlank(deviceShadow.getDeviceCode()) && deviceShadow.getProperties() != null) {
                    String deviceCode = deviceShadow.getDeviceCode();

                    deviceSubscriptionFactory.broadcastToDevice(deviceCode, message);
                }
            } catch (JsonProcessingException e) {
                log.error("[影子设备消息监听]-序列化异常。异常信息:{}", e.getMessage());
            }
        }
    }
}
